//根据2018.03.01日 张家港客户需求改版的要求，在新的后台框架中提供以下功能

//新增
function addOutDataList(id){
	var str = '<tr>'+
		'<td>'+
		    '<select name="modules" lay-verify="required" lay-search="">'+
	          '<option value="">直接选择或搜索选择</option>'+
	          '<option value="1">layer</option>'+
	          '<option value="2">form</option>'+
	          '<option value="3">layim</option>'+
	          '<option value="4">element</option>'+
	          '<option value="5">laytpl</option>'+
	          '<option value="6">upload</option>'+
	          '<option value="7">laydate</option>'+
	          '<option value="8">laypage</option>'+
	          '<option value="9">flow</option>'+
	          '<option value="10">util</option>'+
	          '<option value="11">code</option>'+
	          '<option value="12">tree</option>'+
	          '<option value="13">layedit</option>'+
	          '<option value="14">nav</option>'+
	          '<option value="15">tab</option>'+
	          '<option value="16">table</option>'+
	          '<option value="17">select</option>'+
	          '<option value="18">checkbox</option>'+
	          '<option value="19">switch</option>'+
	          '<option value="20">radio</option>'+
	        '</select>'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
			'<a class="layui-btn layui-btn-xs" onclick="delCustomList(this)">删除</a>'+
		'</td>'+
	'</tr>';
	$("#"+id).append(str);
	layui.use(['form','laydate'], function() {
		var form = layui.form;
		
		form.render();
	});
	//重新初始化Iframe的高度
	cframeInit();
}

//新增
function addIntoDataList(id){
	var str = '<tr>'+
		'<td>'+
		    '<select name="modules" lay-verify="required" lay-search="">'+
	          '<option value="">直接选择或搜索选择</option>'+
	          '<option value="1">layer</option>'+
	          '<option value="2">form</option>'+
	          '<option value="3">layim</option>'+
	          '<option value="4">element</option>'+
	          '<option value="5">laytpl</option>'+
	          '<option value="6">upload</option>'+
	          '<option value="7">laydate</option>'+
	          '<option value="8">laypage</option>'+
	          '<option value="9">flow</option>'+
	          '<option value="10">util</option>'+
	          '<option value="11">code</option>'+
	          '<option value="12">tree</option>'+
	          '<option value="13">layedit</option>'+
	          '<option value="14">nav</option>'+
	          '<option value="15">tab</option>'+
	          '<option value="16">table</option>'+
	          '<option value="17">select</option>'+
	          '<option value="18">checkbox</option>'+
	          '<option value="19">switch</option>'+
	          '<option value="20">radio</option>'+
	        '</select>'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
		    '<input type="tel" name="phone" lay-verify="required" autocomplete="off" class="layui-input">'+
		'</td>'+
		'<td>'+
			'<a class="layui-btn layui-btn-xs" onclick="delCustomList(this)">删除</a>'+
		'</td>'+
	'</tr>';
	$("#"+id).append(str);
	layui.use(['form','laydate'], function() {
		var form = layui.form;
		
		form.render();
	});
	//重新初始化Iframe的高度
	cframeInit();
}

//删除
function delCustomList(_this){
	layui.use(['form','laydate'], function() {
		layer.confirm('确定要删除么？', {
			btn: ['确定', '取消'] //按钮
		}, function() {
			$(_this).parent().parent().remove();
			layer.msg('删除成功', {
				icon: 1
			});
		}, function() {
			layer.msg('取消删除', {
				time: 2000 //20s后自动关闭
			});
		});
	});
}
//--------=======================================================================================================
/**
 * 视图渲染
 * @Param where 渲染位置
 * @Param templateName 模板名
 * @Param data 渲染数据
 * */
function viewToTemplate(where,templateName,data) {
    var html = $('script[type="text/'+templateName+'"]').html();//模板代码
    var arr=[];
    $("#"+where).html("");//清空tbody
    $.each(data, function (index, object) {
        arr.push(formatTemplate(object, html));
    });
    $("#"+where).append(arr.join(""));
}
function formatTemplate(object, tmpl,fun) {
    //m1 匹配到的字符{W} m2 字符的内容 W
    if(tmpl == undefined){
        console.log(tmpl)
        return ;
    }
    return tmpl.replace(/{(\w+)}/g,function (m1, m2) {
        if(!m2){
            return "";
        }
        if(m2 == ""){
            return "";
        }
        if (typeof fun == 'function' ){
            fun();
        }
        return object[m2];
    })
}
function viewToPage(id, templateName, data,condicton){
    var res = data;
    console.log(res)
    viewToTemplate(id,templateName,res.list)
    makePage(res,condicton);
    build_page_nav(res,condicton);
}
/**
 * 分页
 */
function makePage(result){
    $("#page_Info").empty();
    var center=$("<center></center>").append("当前第"+result.pageNum+"页,总共"+result.pages+
        " 页,总"+result.total+" 条数记录");
    $("#page_Info").append(center);

}
function build_page_nav(result,condition){
    $("#page_nav").empty();
    var ul=$("<ul></ul>").addClass("pagination");
    var firstPage=$("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
    var prePage=$("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#"));
    if(result.hasPreviousPage==false){
        firstPage.addClass("disabled");
        prePage.addClass("disabled");
    }else{
        //为元素添加点击事件
        firstPage.click(function(){
            to_Page(1,condition);
        });
        prePage.click(function(){
            to_Page(result.pageNum-1,condition);
        });
    }


    var nextPage=$("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#"));
    var lastPage=$("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
    if(result.hasNextPage==false){
        nextPage.addClass("disabled");
        lastPage.addClass("disabled");
    }else{
        lastPage.click(function(){
            to_Page(result.pages,condition);
        });
        nextPage.click(function(){
            to_Page(result.pageNum+1,condition);
        });
    }


    ul.append(firstPage).append(prePage);
    $.each(result.navigatepageNums,function(index,item){
        var num=$("<li></li>").append($("<a></a>").append(item).attr("href","#"));
        if(result.pageNum==item){
            num.addClass("active");
        }
        num.click(function(){
            to_Page(item,condition);
        });
        ul.append(num);
    });
    ul.append(nextPage).append(lastPage);
    var nav=$("<nav></nav>").addClass("Page navigation").append(ul);
    nav.appendTo("#page_nav");
}
function to_Page(pn, condition){
    var data;
    condition.pn = pn;
    $.ajax({
        url:"/product/getProducts",
        data:condition,
        type:"post",
        success:function(res){
            var res = getOrder(condition,1);
            renderOrderView(res);
        }
    })
}
/**
 * 获取时间
 * @param cellval
 * @returns {string}
 * @constructor
 */
function ChangeDateFormat(cellval) {
    var date = new Date(parseInt(cellval, 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}
//order数据合成
function dataChange(order1,address,user) {
    var order = [order1]
    for(var i = 0; i<order.length; i++){
        var keys = Object.keys(order[i]);
        if(order[i].userId == user.userId){
            order[i].userName = user.name;
            order[i].userPhone = address.phone
        }
        if(order[i].addressId == address.addressId){
            order[i].addressDetail = address.province+address.city+address.country+address.street;
            order[i].addressPhone = address.phone
        }

        for(var j=0; j<keys.length; j++){
            if(keys[j].search("Time") != -1){
                var key = keys[j];
                if(order[i][key] == null){
                    if(key == "paymentTime"){
                        order[i][key]="未支付"
                    }else if(key == "consignTime"){
                        order[i][key]="未发货";
                    }else{
                        order[i][key]="";
                    }

                }else{
                    order[i][key] =ChangeDateFormat(order[i][key])
                }

            }
        }
        order[i].totalPrice = parseInt(order[i].totalPrice)/100
        order[i].payment = (parseInt(order[i].payment))/100;
        if(order[i].status == "0"){
            order[i].status ="未支付"
            order[i].fun = "";
        }else if(order[i].status == "1"){
            order[i].status = "已支付";
            order[i].fun = '<input type="button" class="layui-btn layui-btn-xs" onclick="confirmOrder(\''+order[i].orderId+'\')" value="确定发货">'+'<input type="button" class="layui-btn layui-btn-xs" onclick="orderDetails(\''+order[i].orderId+'\','+order[i].userId+','+order[i].addressId+')" value="详情">'
        }else if(order[i].status == "2"){
            order[i].status = "已发货";
            order[i].fun = '<input type="button" class="layui-btn layui-btn-xs" onclick="orderDetails(\''+order[i].orderId+'\','+order[i].userId+','+order[i].addressId+')" value="详情">'
        }else{
            order[i].status = "已收货";
            order[i].fun = '<input type="button" class="layui-btn layui-btn-xs" onclick="delOrder(\''+order[i].orderId+'\')" value="删除">'+'<input type="button" class="layui-btn layui-btn-xs" onclick="orderDetails(\''+order[i].orderId+'\','+order[i].userId+','+order[i].addressId+')" value="详情">'
        }
        if(order[i].discount == null || order[i].discount == "" ){
            order[i].discount = parseInt(order[i].totalPrice);
        }else{
            order[i].discount = parseInt(order[i].discount)/100;
        }
        if(order[i].orderProducts == null){
            order[i].orderProducts = "";
        }
    }
    return order;
}
//orderProduct合成数据
function dataParseOrderProduct(data) {
    for(var i =0; i<data.length; i++){
        data[i].totalPrice = parseInt(data[i].totalPrice) / 100;
        data[i].onePrice = parseInt(data[i].onePrice) / 100;
    }
    return data;
}
//获取order数据
function getOrder(order,pn) {
    var data = {};
    order.pn = pn;
    // order.status = 0;
	$.ajax({
        url:"/order/queryOrder",
        type:'post',
        async : false,
        data:order,
        success:function (res) {
            if(res.code == "200"){
               data = res;
            }else {
                alert(res.msg)
            }
        }
    });
    return data;
}
//获取orderProduct数据
function getOrderProduct(orderProduct) {
    var data = {};
    $.ajax({
        url:"/orderProduct/queryOrderProducts",
        type:'post',
        async : false,
        data:orderProduct,
        success:function (res) {
            if(res.code == "200"){
                data = res;
            }else {
                alert(res.msg)
            }
        }
    });
    return data;
}
//获取user数据
function getUser(user) {
    var data = {};
    $.ajax({
        url:"/user/getUserById",
        type:'post',
        async : false,
        data:user,
        success:function (res) {
            if(res.code == "200"){
                data = res.extend.user;
            }else {
                alert(res.msg)
            }
        }
    })
    return data;
}
//获取address数据
function getAddress(address) {
    var data = {};
    $.ajax({
        url:"/address/queryAddressById",
        type:'post',
        async:false,
        data:address,
        success:function (res) {
            if(res.code == "200"){
                data = res.extend.address;
            }else {
                alert(res.msg)
            }
        }
    })
    return data;
}

//order数据渲染
function renderOrderView(res,order) {
    var user = {},
        address = {},
        renderData = {};
    renderData =res.extend.orders;
    res= res.extend.orders.list;
    console.log(res)
    if(res.length>0){
        for(var i=0;i<res.length; i++){
            user.userId = res[0].userId;
            address.addressId = res[0].addressId
            user = getUser(user);
            address = getAddress(address);
            renderData.list = dataChange(res[0],address,user);
            viewToPage("order_tbody","order_tbody",renderData,order);
        }
    }else{
        $("#order_tbody").html("没有订单")
    }
}
//模态框orderProduct渲染
function renderOrderProductModalView(data) {
    var res = data.extend.orderProducts;
    res = dataParseOrderProduct(res)
    viewToTemplate("orderProduct_tbody","orderProduct_tbody",res);
    $("#exampleModal").modal("show");
}
//功能--模态框数据打开
function orderProduct_modal(id) {
    var orderProduct = {},
        data ={};
    orderProduct.orderId = id;
    data = getOrderProduct(orderProduct);

    renderOrderProductModalView(data)
}

//功能--确定收货
function confirmOrder(id){
    var status = $("#status_"+id).html();
    if(status == "未支付"){
        alert("用户还未支付")
    }else if(status == "已支付"){
        $.ajax({
            url:"/order/confirmOrder",
            async : false,
            type:"post",
            data:{"orderId":id,"status":2},
            success:function (res) {
                console.log(res)
                if(res.code == "200"){
                    var order = {};
                    order.orderId = id;
                    var pn = $("li:active > a").text();
                    console.log(pn)
                    var res = getOrder(order,pn);
                    renderOrderView(res);
                    alert("发货成功")
                }else {
                    alert(res.msg);
                }
            }
        })
    }else{
        alert("您已发货")
    }

}
//功能--订单详情
function orderDetails(id,userId,addressId){
   orderProduct_modal(id);
}
//查看状态
function setStatus(status){
    var order = {};
    if(status == '4'){
        order = {}
    }else {
        order.status = status;
    }

    var data = getOrder(order,1);
    renderOrderView(data,order);
}
$(document).ready(function () {
    var order = {};
    var res = getOrder(order,1);
    renderOrderView(res);
    $("#exampleModal").on("hide.bs.modal",function () {
        $("#orderProduct_tbody").empty();
    })
})

